//
//  MarketJaDbOperator.m
//  MarketDataColloctor
//
//  Created by jiro on 10/02/20.
//  Copyright 2010 jiro music. All rights reserved.
//

#import "MarketJaDbOperator.h"
//#import "../DbConstants.h"
#import "../DbTypes.h"

@implementation MarketJaDbOperator

+ (DbOperator*) defaultOperator
{
	return [ DbOperator defaultOperator ];
}

+ (StockBrandJaList*) allBrandCodes: (BOOL) existFlag
{
	DbOperator* dbOperator = [ MarketJaDbOperator defaultOperator ];

	StockBrandJaList* stockBrandCodes = nil;
	NSString* sqlQuery = [ NSString stringWithFormat: 
		@"select * from %@ where %@ = %@ order by %@;",
		kText_StockBrandJaTable, kText_ExistFlag, existFlag ? @"true" : @"false", kText_Code ];
	PGresult* res;
	if ( DbResponse_Success != [ dbOperator executeQuery: sqlQuery intoResult: & res ] )
	{
		stockBrandCodes = nil;
	}
	else
	{
		stockBrandCodes = [ StockBrandJaList stockBrandJaListWithPgResult: res ];
	}
	PQclear( res );

	[ dbOperator disconnect ];
	return stockBrandCodes;
}

+ (CurrencyTypeList) allCurrencyTypes
{
	DbOperator* dbOperator = [ MarketJaDbOperator defaultOperator ];

	CurrencyTypeList types;
	NSString* sqlQuery = [ NSString stringWithFormat: 
		@"select * from %@;", CurrencyType::tableName() ];
	PGresult* res;
	if ( DbResponse_Success != [ dbOperator executeQuery: sqlQuery intoResult: & res ] )
	{
		types = nil;
	}
	else
	{
		types = CurrencyTypeList( res );
	}
	PQclear( res );

	[ dbOperator disconnect ];
	return types;	
}

+ (CurrencyExchangeTypeList) allCurrencyExchangeTypes
{
	DbOperator* dbOperator = [ MarketJaDbOperator defaultOperator ];

	CurrencyExchangeTypeList types;
	NSString* sqlQuery = [ NSString stringWithFormat: 
		@"select * from %@;", CurrencyExchangeType::tableName() ];
	PGresult* res;
	if ( DbResponse_Success != [ dbOperator executeQuery: sqlQuery intoResult: & res ] )
	{
		types = nil;
	}
	else
	{
		types = CurrencyExchangeTypeList( res );
	}
	PQclear( res );

	[ dbOperator disconnect ];
	return types;
}

+ (DataCollectLogList*) allDataCollectLog: (MarketData::Type) marketDataType
{
	DbOperator* dbOperator = [	MarketJaDbOperator defaultOperator ];

	DataCollectLogList* logs = nil;
	NSString* sqlQuery = [ NSString stringWithFormat: 
		@"select * from %@ where %@ = %d order by %@ desc;" , 
		[ DataCollectLog tableName ], kText_MarketDataType, marketDataType, kText_Code0 ];
	PGresult* res;
	if ( DbResponse_Success != [ dbOperator executeQuery: sqlQuery intoResult: & res ] && 
		 DbResponse_SuccessWithWarning != [ dbOperator executeQuery: sqlQuery intoResult: & res ] )
	{
		logs = nil;
		NSLog( @"%@", [ dbOperator errorMessage ] );
	}
	else
	{
		logs = [ DataCollectLogList dataCollectLogListWithPgResult: res ];
	}
	PQclear( res );

	[ dbOperator disconnect ];
	return logs;	
	
}

@end
